package com.atlin.project.utils.ip;

import com.atlin.project.config.AtLinConfig;
import com.atlin.project.contant.CommonConstant;
import com.atlin.project.utils.HttpUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 获取地址类
 *
 * @author atlin
 */
@Slf4j
public class AddressUtils {

    /**
     * IP 地址查询
     */
    private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 未知地址
     */
    private static final String UNKNOWN = "XX XX";

    private final static Gson GSON = new Gson();

    /**
     * 通过IP获取真实地址
     *
     * @return 真实地址
     */
    public static String getRealAddressByIP(String ip) {
        if (NetUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (AtLinConfig.isAddressEnable()) {
            try {
                String resStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", CommonConstant.GBK);
                if (StringUtils.isEmpty(resStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                Map<String, String> map = GSON.fromJson(resStr, Map.class);
                String region = map.get("pro");
                String city = map.get("city");
                String addr = map.get("addr");
                String address = String.format("%s %s", region, city);

                return StringUtils.isBlank(address) ? addr.trim() : address;
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }
}
